package service

import (
	"bytes"
	"crypto/cipher"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"

	// "fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"diff.wang/wdhealthcard/config"
	dto "diff.wang/wdhealthcard/dto/third"
	"diff.wang/wdhealthcard/global"
	"diff.wang/wdhealthcard/utils"
	"github.com/gin-gonic/gin"
	"github.com/tjfoc/gmsm/sm2"
	"github.com/tjfoc/gmsm/sm4"
	"github.com/tjfoc/gmsm/x509"
)

// 私密方法，内部进行国密 sm2 加密
func innerSm2Encrypt(str string) (string, error) {
	b1, err := ioutil.ReadFile("./certs/pubKey.pem")
	if err != nil {
		global.ZAPLOGGER.Error("read public Key failed, err:" + err.Error())
		return "", err
	}
	pk, err := x509.ReadPublicKeyFromPem(b1)
	if err != nil {
		global.ZAPLOGGER.Error("read public Key From Pem failed, err:" + err.Error())
		return "", err
	}

	// C1C3C2=0   C1C2C3=1
	b, err := sm2.Encrypt(pk, []byte(str), nil, 1)
	if err != nil {
		global.ZAPLOGGER.Error("sm2 encrypt failed, err:" + err.Error())
		return "", err
	}
	s := hex.EncodeToString(b)
	return strings.ToUpper(s), nil
}

// 内部获取 token
func innerGetToken() (string, error) {

	s, err := innerSm2Encrypt(config.Conf.HealthCard["ertong"].SecretKey)
	if err != nil {
		return "", err
	}

	reqToken := new(dto.GetTokenDTO)
	reqToken.AppId = config.Conf.HealthCard["ertong"].AppId
	reqToken.Method = "token"
	reqToken.Version = "v1.10"
	reqToken.Timestamp = time.Now().UnixMilli()
	reqToken.DigestType = "SM2"
	reqToken.EncType = "SM4"
	reqToken.Ext = ""
	reqToken.BizContent.Secret = s

	b2, err := json.Marshal(reqToken)
	if err != nil {
		global.ZAPLOGGER.Error("json marshal reqToken failed, err:" + err.Error())
		return "", err
	}

	// 发送请求
	url := global.WdHealthCardUrl + global.WdHealthCardGetToken
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		global.ZAPLOGGER.Error("post failed, err:" + err.Error())
		return "", err
	}
	defer resp.Body.Close()
	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		global.ZAPLOGGER.Error("get resp failed,err:" + err.Error())
		return "", err
	}

	var res = new(dto.TokenRespDataDTO)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		global.ZAPLOGGER.Error("json marshal resByte failed,err:" + err.Error())
		return "", err
	}

	if res.RespCode == global.WdHealthCardResCode {
		global.ZAPLOGGER.Info("inner get Token Success, value: " + res.RespData.BizContent.Token)
		return res.RespData.BizContent.Token, nil
	}
	return "", errors.New(res.RespDesc)
}

func innerGenBaseQueryParams(method string) (*dto.EcardDTOReq, string, error) {
	var req dto.EcardDTOReq
	req.AppId = config.Conf.HealthCard["ertong"].AppId
	req.Method = method
	req.Version = "v1.10"
	req.Timestamp = time.Now().UnixMilli()
	req.DigestType = "SM2"
	req.EncType = "SM4"
	req.Ext = ""

	// 获得 token
	tokenString, err := innerGetToken()
	if err != nil {
		global.ZAPLOGGER.Error("inner get token failed,err:" + err.Error())
		return nil, "", err
	}
	fmt.Println(tokenString)

	// 对 token 签名(加密) SM2
	digestString, err := innerSm2Encrypt(tokenString)
	if err != nil {
		global.ZAPLOGGER.Error("inner sm2 Encrypt failed,err:" + err.Error())
		return nil, "", err
	}
	req.Digest = digestString
	return &req, tokenString, nil
}

//明文数据填充  pkcs7Padding blockSize 16  |  pkcs5Padding blockSize 8
func paddingLastGroup(plainText []byte, blockSize int) []byte {
	//1.计算最后一个分组中明文后需要填充的字节数
	padNum := blockSize - len(plainText)%blockSize
	//2.将字节数转换为byte类型
	char := []byte{byte(padNum)}
	//3.创建切片并初始化
	newPlain := bytes.Repeat(char, padNum)
	//4.将填充数据追加到原始数据后
	newText := append(plainText, newPlain...)

	return newText
}

//去掉明文后面的填充数据   pkcs7Padding blockSize 16  |  pkcs5Padding blockSize 8
func unpaddingLastGroup(plainText []byte) []byte {
	//1.拿到切片中的最后一个字节
	length := len(plainText)
	lastChar := plainText[length-1]
	//2.将最后一个数据转换为整数
	number := int(lastChar)
	return plainText[:length-number]
}

func sm4Encrypt(plainText, key []byte) []byte {
	block, err := sm4.NewCipher(key)
	if err != nil {
		panic(err)
	}
	fmt.Println(block.BlockSize())
	paddData := paddingLastGroup(plainText, block.BlockSize())
	iv := []byte("12345678qwertyui")
	blokMode := cipher.NewCBCEncrypter(block, iv)
	cipherText := make([]byte, len(paddData))
	blokMode.CryptBlocks(cipherText, paddData)
	return cipherText
}

func sm4Dectypt(cipherText, key []byte) []byte {
	block, err := sm4.NewCipher(key)
	if err != nil {
		panic(err)
	}
	iv := []byte("12345678qwertyui")
	blockMode := cipher.NewCBCDecrypter(block, iv)
	blockMode.CryptBlocks(cipherText, cipherText)
	plainText := unpaddingLastGroup(cipherText)
	return plainText
}

// GetToken
// @Summary 获取Token
// @Schemes
// @Description 获取Token
// @Tags 万达健康
// @Accept json
// @Produce json
// @Router /v1/getToken [get]
func GetToken(c *gin.Context) {

	b1, err := ioutil.ReadFile("./certs/pubKey.pem")
	if err != nil {
		utils.Fail(c, "read public Key failed, err:"+err.Error())
		return
	}
	pk, err := x509.ReadPublicKeyFromPem(b1)
	if err != nil {
		utils.Fail(c, "read public Key From Pem failed, err:"+err.Error())
		return
	}

	b, err := sm2.Encrypt(pk, []byte(config.Conf.HealthCard["ertong"].SecretKey), nil, 1)
	if err != nil {
		utils.Fail(c, "sm2 encrypt failed, err:"+err.Error())
		return
	}
	s := hex.EncodeToString(b)
	reqToken := new(dto.GetTokenDTO)
	reqToken.AppId = config.Conf.HealthCard["ertong"].AppId
	reqToken.Method = "token"
	reqToken.Version = "v1.10"
	reqToken.Timestamp = time.Now().UnixMilli()
	reqToken.DigestType = "SM2"
	reqToken.EncType = "SM4"
	reqToken.Ext = ""
	reqToken.BizContent.Secret = strings.ToUpper(s)

	b2, err := json.Marshal(reqToken)
	if err != nil {
		utils.Fail(c, "json marshal reqToken failed, err:"+err.Error())
		return
	}
	// fmt.Println(string(b2))

	url := global.WdHealthCardUrl + global.WdHealthCardGetToken
	contentType := global.WdHealthCardContentType
	// data := string(b2)
	// resp, err := http.Post(url, contentType, strings.NewReader(data))
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()
	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}

	var res = new(dto.TokenRespDataDTO)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}
	// fmt.Println(string(resByte))

	utils.SuccessStruct(c, res)
}

func zeroPadding(in []byte) []byte {
	length := len(in)
	if length%8 == 0 {
		return in
	} else {
		blockCount := length / 8
		out := make([]byte, (blockCount+1)*8)
		var i int
		for i = 0; i < length; i++ {
			out[i] = in[i]
		}
		return out
	}
}

func zeroUnPadding(in []byte) []byte {
	return bytes.TrimRight(in, string([]byte{0}))
}

// nodding模式，只填充到能存下src的最小的16字节的整数倍。
// 比如：src 10字节，填充到16字节；src 16字节，则不再填充
func noPadding(in []byte) []byte {

	paddingNum := 16 - len(in)%16
	if len(in)%16 == 0 {
		return in
	} else {
		return append(in, bytes.Repeat([]byte{' '}, paddingNum)...)
	}
}

func noUnPadding(in []byte) []byte {
	for i := len(in) - 1; ; i-- {
		if in[i] != ' ' {
			return in[:i+1]
		}
	}
}

// Ecard
// @Summary 电子健康卡注册查询参数
// @Schemes
// @Description 2.4.1电子健康卡注册查询参数（Json 对象）
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.EcardEntry true "电子健康卡注册查询实体"
// @Success 200 {object}  dto.EcardEntryRes
// @Router /v1/ecard/regquery [post]
func EcardRegquery(c *gin.Context) {

	// 接收数据
	var jsonReq dto.EcardEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("regquery")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// pkcs7 填充
	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	/* cx, _ := sm4.Sm4Ecb([]byte(tokenString), cipherTextByteSlice, false)
	fmt.Println("jiemi", string(cx)) */

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}
	// fmt.Printf("%#v \n", res)

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密", string(cx))
		ecardEntryRes := new(dto.EcardEntryRes)
		err = json.Unmarshal(cx, &ecardEntryRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = *ecardEntryRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	// ecardEntryRes := new(dto.EcardEntry)

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 获取电子健康卡二维码图片
// @Schemes
// @Description 2.3.2获取电子健康卡二维码图片接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.EcardApplyEntry true "获取电子健康卡二维码图片查询实体"
// @Success 200 {object}  dto.EcardApplyRes
// @Router /v1/ecard/apply [post]
func EcardApply(c *gin.Context) {

	// 接收数据
	var jsonReq dto.EcardApplyEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardApplyEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("apply")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		ecardApplyRes := new(dto.EcardApplyRes)
		err = json.Unmarshal(cx, &ecardApplyRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardApplyRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = *ecardApplyRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 用户信息修改
// @Schemes
// @Description 2.3.3用户信息修改接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.EcardModifyEntry true "用户信息修改实体"
// @Success 200 {object}  dto.EcardModifyRes
// @Router /v1/ecard/modify [post]
func EcardModify(c *gin.Context) {

	// 接收数据
	var jsonReq dto.EcardModifyEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardModifyEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("modify")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		ecardModifyRes := new(dto.EcardModifyRes)
		err = json.Unmarshal(cx, &ecardModifyRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardModifyRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = *ecardModifyRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 绑卡接口
// @Schemes
// @Description 2.3.4绑卡接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.EcardBindEntry true "绑卡接口实体"
// @Success 200 {object}  []dto.EcardBindRes
// @Router /v1/ecard/bind [post]
func EcardBind(c *gin.Context) {

	// 接收数据
	var jsonReq dto.EcardBindEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardBindEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("bind")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		ecardBindRes := make([]dto.EcardBindRes, 5)
		err = json.Unmarshal(cx, &ecardBindRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = ecardBindRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 绑卡信息查询接口
// @Schemes
// @Description 2.3.5绑卡信息查询接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.CardFindEntry true "绑卡信息查询接口实体"
// @Success 200 {object}  []dto.CardEntry
// @Router /v1/ecard/bindCards [post]
func EcardBindCards(c *gin.Context) {

	// 接收数据
	var jsonReq dto.CardFindEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardBindEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("bindCards")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		ecardBindRes := make([]dto.CardEntry, 10)
		err = json.Unmarshal(cx, &ecardBindRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = ecardBindRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 刷新令牌接口
// @Schemes
// @Description 2.3.6刷新令牌接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.SecretDTO true "刷新令牌接口实体"
// @Success 200 {object}  dto.TokenDTO
// @Router /v1/ecard/refresh [post]
func EcardRefresh(c *gin.Context) {
	
	// 接收数据
	var jsonReq dto.SecretDTO
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind SecretDTO failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("refresh")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		tokenDTO := new(dto.TokenDTO)
		err = json.Unmarshal(cx, &tokenDTO)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = *tokenDTO
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 获取接入机构接口
// @Schemes
// @Description 2.3.7获取接入机构接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.AccessOrgsEntry true "获取接入机构接口实体"
// @Success 200 {object}  dto.AccessOrgsRes
// @Router /v1/ecard/accessOrgs [post]
func EcardAccessOrgs(c *gin.Context) {
	// 接收数据
	var jsonReq dto.AccessOrgsEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind AccessOrgsEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("accessOrgs")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		accessOrgsRes := make([]dto.AccessOrgsRes, 10)
		err = json.Unmarshal(cx, &accessOrgsRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = accessOrgsRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 用卡记录接口
// @Schemes
// @Description 2.3.8用卡记录接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.EcardApplyEntry true "用卡记录接口接口实体"
// @Success 200 {object}  dto.AccessOrgsRes
// @Router /v1/ecard/useCardLog [post]
func EcardUseCardLog(c *gin.Context) {

	// 接收数据
	var jsonReq dto.EcardApplyEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind EcardApplyEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("useCardLog")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	// fmt.Println("请求参数",string(b2))
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		useCardLogRes := make([]dto.UseCardLogRes, 10)
		err = json.Unmarshal(cx, &useCardLogRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = useCardLogRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}

// Ecard
// @Summary 互联网用卡数据接口
// @Schemes
// @Description 2.3.9互联网用卡数据接口
// @Tags 万达健康
// @Accept json
// @Produce json
// @Param ecardData body dto.VerifyEntry true "互联网用卡数据接口实体"
// @Success 200 {object}  dto.VerifyRes
// @Router /v1/ecard/verify [post]
func EcardVerify(c *gin.Context) {
	
	// 接收数据
	var jsonReq dto.VerifyEntry
	if err := c.ShouldBindJSON(&jsonReq); err != nil {
		utils.Fail(c, "bind VerifyEntry failed,err:"+err.Error())
		return
	}
	b, err := json.Marshal(jsonReq)
	if err != nil {
		utils.Fail(c, "reqest Marshal failed, err:"+err.Error())
		return
	}

	ed, tokenString, err := innerGenBaseQueryParams("verify")
	if err != nil {
		utils.Fail(c, "call innerGenBaseQueryParams failed,err:"+err.Error())
		return
	}

	// 对内容签名(加密) SM4
	// pkcs7 填充

	// cipherText 密文 byte
	cipherTextByteSlice, _ := sm4.Sm4Ecb([]byte(tokenString), b, true)
	ed.BizContent = hex.EncodeToString(cipherTextByteSlice)

	// 发送请求
	b2, err := json.Marshal(*ed)
	if err != nil {
		utils.Fail(c, "json marshal req failed, err:"+err.Error())
		return
	}
	url := global.WdHealthCardUrl + global.WdHealthCardEcard
	contentType := global.WdHealthCardContentType
	resp, err := http.Post(url, contentType, bytes.NewReader(b2))
	if err != nil {
		utils.Fail(c, "post failed, err:"+err.Error())
		return
	}
	defer resp.Body.Close()

	resByte, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		utils.Fail(c, "get resp failed,err:"+err.Error())
		return
	}
	var res = new(dto.WdBaseDTORes)
	err = json.Unmarshal(resByte, &res)
	if err != nil {
		utils.Fail(c, "json marshal resByte failed,err:"+err.Error())
		return
	}

	if res.RespCode == global.WdHealthCardResCode {
		secretHex := fmt.Sprintf("%v", res.RespData.BizContent)
		b3, err := hex.DecodeString(secretHex)
		if err != nil {
			utils.Fail(c, "secretHex to String failed,err:"+err.Error())
			return
		}
		cx, err := sm4.Sm4Ecb([]byte(tokenString), b3, false)
		if err != nil {
			utils.Fail(c, "Sm4Ecb cx failed,err:"+err.Error())
			return
		}
		// fmt.Println("解密",string(cx))
		verifyRes := new(dto.VerifyRes)
		err = json.Unmarshal(cx, &verifyRes)
		if err != nil {
			utils.Fail(c, "json unMarshal cx to ecardBindRes failed,err:"+err.Error())
			return
		}
		res.RespData.BizContent = *verifyRes
		// fmt.Printf("%#v \n", res)
		retJson, _ := json.Marshal(res)
		c.Data(http.StatusOK, global.WdHealthCardContentType, retJson)
		return
	}

	c.Data(200, global.WdHealthCardContentType, resByte)
}
